﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Globalization;

namespace GameDBManager
{
	public partial class Export : Apq.Windows.Forms.ImeForm
	{
		[Obsolete("仅为能打开设计视图而保留")]
		private Export()
		{
			InitializeComponent();
		}

		public int ExcelMaxRowNumber = 65500;

		public override void SetUILang(Apq.UILang.UILang UILang)
		{
			Text = UILang["导出"];

			lblRowCount.Text = UILang["共有行数:  "];
			lblFileType.Text = UILang["导出类型:"];

			groupBox1.Text = UILang["导出选项"];
			lblColSpliter.Text = UILang["列分隔符:"];
			lblRowSpliter.Text = UILang["行分隔符:"];
			cbContainsColName.Text = UILang["首行为列名"];
			cbContainsDBIID.Text = UILang["包含DBIID"];
			cbContainsDBIName.Text = UILang["包含DBIName"];

			btnConfirm.Text = UILang["确定"];
			btnClose.Text = UILang["关闭"];
		}

		/// <summary>
		/// Export
		/// </summary>
		/// <param name="ds">数据集</param>
		public Export(DataSet ds)
		{
			InitializeComponent();

			this.ds = ds;
			foreach (DataTable dt in ds.Tables)
			{
				RowCount += dt.Rows.Count;
				MaxRowCount = MaxRowCount > dt.Rows.Count ? MaxRowCount : dt.Rows.Count;
			}
		}

		private DataSet _ds;
		/// <summary>
		/// 获取或设置导出数据集
		/// </summary>
		public DataSet ds
		{
			get { return _ds; }
			set { _ds = value; }
		}

		private long RowCount = 0;
		private int MaxRowCount = 0;

		private void Export_Load(object sender, EventArgs e)
		{
			//ShowInTaskbar = false;
			Icon = new Icon(Application.StartupPath + @"\Res\ico\sign141.ico");

			lblRowCount.Text += RowCount;

			cbExportType.SelectedIndex = Apq.Convert.ChangeType<int>(GlobalObject.XmlConfigChain[this.GetType(), "cbExportType"]);
			cbContainsColName.Checked = Apq.Convert.ChangeType<bool>(GlobalObject.XmlConfigChain[this.GetType(), "cbContainsColName"], true);
			cbContainsDBIID.Checked = Apq.Convert.ChangeType<bool>(GlobalObject.XmlConfigChain[this.GetType(), "cbContainsDBIID"], true);
			cbContainsDBIName.Checked = Apq.Convert.ChangeType<bool>(GlobalObject.XmlConfigChain[this.GetType(), "cbContainsDBIName"], true);

			if (MaxRowCount > ExcelMaxRowNumber)
			{
				MessageBox.Show("存在最大行数超过 Excel 所支持的最大行数的表,导出为 Excel 时将自动导出分割为多个 Sheet。\r\n建议导出为文本文件.", "提示", MessageBoxButtons.OK);
			}
		}

		private void Export_FormClosed(object sender, FormClosedEventArgs e)
		{
			GlobalObject.XmlConfigChain.Save();
		}

		// 确定
		private void btnConfirm_Click(object sender, EventArgs e)
		{
			sfd.InitialDirectory = GlobalObject.XmlConfigChain[this.GetType(), "sfd_InitialDirectory"];
			if (sfd.ShowDialog(this) == DialogResult.OK)
			{
				GlobalObject.XmlConfigChain[this.GetType(), "sfd_InitialDirectory"] = System.IO.Path.GetDirectoryName(sfd.FileName);

				tsslStatus.Text = "导出中...";
				int RowCount = 0;
				foreach (DataTable dt in ds.Tables)
				{
					RowCount += dt.Rows.Count;
				}
				tspbProcess.Value = 0;
				tspbProcess.Maximum = RowCount;

				if (cbExportType.SelectedIndex == 0)
				{
					if (!ExportToText()) return;
				}
				if (cbExportType.SelectedIndex == 1)
				{
					if (!ExportToExcel()) return;
				}
				if (cbExportType.SelectedIndex == 2)
				{
					if (!ExportToMsSql()) return;
				}
				if (cbExportType.SelectedIndex == 3)
				{
					if (!ExportToMySql()) return;
				}
				tsslStatus.Text = "导出完成";

				try
				{
					// 显示文件
					Process.Start(Apq.Dos.Common.EncodeParam(sfd.FileName));
				}
				catch { }

				//this.Close();
			}
		}

		private bool ExportToText()
		{
			tspbProcess.Maximum += cbContainsColName.Checked ? ds.Tables.Count : 0;

			string strColSpliter = cbColSpliter.Text;
			string strRowSpliter = cbRowSpliter.Text;
			// 输入检测:信息完整性
			if (strColSpliter.Length < 1)
			{
				MessageBox.Show("请设置正确的列分隔符");
				cbColSpliter.Focus();
				return false;
			}
			if (strRowSpliter.Length < 1)
			{
				MessageBox.Show("请设置正确的行分隔符");
				cbRowSpliter.Focus();
				return false;
			}

			//分隔符转换
			switch (strColSpliter)
			{
				case "\\t":
					strColSpliter = "\t";
					break;
			}
			switch (strRowSpliter)
			{
				case "\\r\\n":
					strRowSpliter = "\r\n";
					break;
			}

			//StreamWriter sw = File.CreateText(sfd.FileName);//此方法生成的文档是UTF-8 no BOM
			StreamWriter sw = new StreamWriter(sfd.FileName, false, new UTF8Encoding(true));
			// 执行导出
			try
			{
				foreach (DataTable dt in ds.Tables)
				{
					int nColCount = dt.Columns.Count;
					if (!cbContainsDBIID.Checked) nColCount--;
					if (!cbContainsDBIName.Checked) nColCount--;

					if (cbContainsColName.Checked)
					{
						for (int i = 0; i < dt.Columns.Count; i++)
						{
							if (dt.Columns[i].ColumnName == "__DBIID" && !cbContainsDBIID.Checked)
							{
								continue;
							}
							if (dt.Columns[i].ColumnName == "__DBIName" && !cbContainsDBIName.Checked)
							{
								continue;
							}

							DataColumn dc = dt.Columns[i];
							sw.Write(dc.ColumnName);
							if (i < nColCount - 1)
							{
								sw.Write(strColSpliter);
							}
						}
						sw.Write(strRowSpliter);
						sw.Flush();

						tspbProcess.Value++;
						Application.DoEvents();
					}
					foreach (DataRow dr in dt.Rows)
					{
						for (int i = 0; i < dr.ItemArray.Length; i++)
						{
							if (dt.Columns[i].ColumnName == "__DBIID" && !cbContainsDBIID.Checked)
							{
								continue;
							}
							if (dt.Columns[i].ColumnName == "__DBIName" && !cbContainsDBIName.Checked)
							{
								continue;
							}

							object obj = dr.ItemArray[i];
							string str = Apq.Data.SqlClient.Common.ConvertToSqlON(obj);
							sw.Write(str);
							if (i < nColCount - 1)
							{
								sw.Write(strColSpliter);
							}
						}
						sw.Write(strRowSpliter);
						sw.Flush();

						tspbProcess.Value++;
						Application.DoEvents();
					}
				}
				return true;
			}
			catch (System.IO.DirectoryNotFoundException)
			{
				MessageBox.Show("文件路径不正确", "输入错误");
				return false;
			}
			finally
			{
				sw.Close();
			}
		}
		private bool ExportToExcel()
		{
			try
			{
				DataSet dsOut = ds.Copy();
				// 整理数据集
				if (!cbContainsDBIID.Checked)
				{
					foreach (DataTable dt in dsOut.Tables)
					{
						dt.Columns.Remove("__DBIID");
					}
				}
				if (!cbContainsDBIName.Checked)
				{
					foreach (DataTable dt in dsOut.Tables)
					{
						dt.Columns.Remove("__DBIName");
					}
				}

				Apq.Data.DataSetHelper.BuildupTabelForMaxrow(dsOut, ExcelMaxRowNumber);

				DataSet dsExcel = new DataSet();
				dsExcel.DataSetName = sfd.FileName;
				foreach (DataTable dt in dsOut.Tables)
				{
					DataTable dtExcel = Apq.Data.DataTable.CloneToStringTable(dt);
					dtExcel.TableName = dt.TableName;
					dsExcel.Tables.Add(dtExcel);

					foreach (DataRow dr in dt.Rows)
					{
						DataRow drExcel = dtExcel.NewRow();
						foreach (DataColumn dc in dt.Columns)
						{
							drExcel[dc.ColumnName] = Apq.Data.SqlClient.Common.ConvertToSqlON(dr[dc]);
						}
						dtExcel.Rows.Add(drExcel);

						tspbProcess.Value++;
						Application.DoEvents();
					}
				}

				org.in2bits.MyXls.XlsDocument xd = new org.in2bits.MyXls.XlsDocument(dsExcel);
				FileStream fs = new FileStream(sfd.FileName, FileMode.Create);
				xd.Save(fs);
				fs.Flush();
				fs.Close();
				return true;
			}
			catch (System.IO.DirectoryNotFoundException)
			{
				MessageBox.Show("文件路径不正确", "输入错误");
				return false;
			}
		}
		private bool ExportToMsSql()
		{
			//StreamWriter sw = File.CreateText(sfd.FileName);//此方法生成的文档是UTF-8 no BOM
			StreamWriter sw = new StreamWriter(sfd.FileName, false, new UTF8Encoding(true));
			// 执行导出
			try
			{
				foreach (DataTable dt in ds.Tables)
				{
					List<string> lstCol = new List<string>();
					for (int i = 0; i < dt.Columns.Count; i++)
					{
						if (dt.Columns[i].ColumnName == "__DBIID" && !cbContainsDBIID.Checked)
						{
							continue;
						}
						if (dt.Columns[i].ColumnName == "__DBIName" && !cbContainsDBIName.Checked)
						{
							continue;
						}

						lstCol.Add("[" + dt.Columns[i].ColumnName + "]");
					}
					string strCols = string.Join(",", lstCol);

					foreach (DataRow dr in dt.Rows)
					{
						sw.Write(string.Format(@"INSERT INTO [{0}]({1})
VALUES(", dt.TableName, strCols));
						for (int i = 0; i < lstCol.Count; i++)
						{
							object obj = dr[lstCol[i].Substring(1, lstCol[i].Length - 2)];
							string str = Apq.Data.SqlClient.Common.ConvertToSqlON(obj);
							sw.Write(str);
							if (i < lstCol.Count - 1)
							{
								sw.Write(",");
							}
						}
						sw.WriteLine(");");
						sw.Flush();

						tspbProcess.Value++;
						Application.DoEvents();
					}

					sw.WriteLine();
					sw.Flush();
				}
				return true;
			}
			catch (System.IO.DirectoryNotFoundException)
			{
				MessageBox.Show("文件路径不正确", "输入错误");
				return false;
			}
			finally
			{
				sw.Close();
			}
		}
		private bool ExportToMySql()
		{
			//StreamWriter sw = File.CreateText(sfd.FileName);//此方法生成的文档是UTF-8 no BOM
			StreamWriter sw = new StreamWriter(sfd.FileName, false, new UTF8Encoding(true));
			// 执行导出
			try
			{
				foreach (DataTable dt in ds.Tables)
				{
					List<string> lstCol = new List<string>();
					for (int i = 0; i < dt.Columns.Count; i++)
					{
						if (dt.Columns[i].ColumnName == "__DBIID" && !cbContainsDBIID.Checked)
						{
							continue;
						}
						if (dt.Columns[i].ColumnName == "__DBIName" && !cbContainsDBIName.Checked)
						{
							continue;
						}

						lstCol.Add("`" + dt.Columns[i].ColumnName + "`");
					}
					string strCols = string.Join(",", lstCol);

					foreach (DataRow dr in dt.Rows)
					{
						sw.Write(string.Format(@"INSERT INTO `{0}`({1})
VALUES(", dt.TableName, strCols));
						for (int i = 0; i < lstCol.Count; i++)
						{
							object obj = dr[lstCol[i].Substring(1, lstCol[i].Length - 2)];
							string str = Apq.Data.MySqlClient.Common.ConvertToSqlON(obj);
							sw.Write(str);
							if (i < lstCol.Count - 1)
							{
								sw.Write(",");
							}
						}
						sw.WriteLine(");");
						sw.Flush();

						tspbProcess.Value++;
						Application.DoEvents();
					}

					sw.WriteLine();
					sw.Flush();
				}
				return true;
			}
			catch (System.IO.DirectoryNotFoundException)
			{
				MessageBox.Show("文件路径不正确", "输入错误");
				return false;
			}
			finally
			{
				sw.Close();
			}
		}

		// 取消
		private void btnClose_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private void cbExportType_SelectedIndexChanged(object sender, EventArgs e)
		{
			GlobalObject.XmlConfigChain[this.GetType(), "cbExportType"] = cbExportType.SelectedIndex.ToString();

			// 设置过滤器
			sfd.FilterIndex = cbExportType.SelectedIndex + 1;
			switch (cbExportType.SelectedIndex)
			{
				case 0:
				default:
					sfd.DefaultExt = "txt";
					break;
				case 1:
					sfd.DefaultExt = "xls";
					break;
				case 2:
					sfd.DefaultExt = "sql";
					break;
				case 3:
					sfd.DefaultExt = "sql";
					break;
			}
		}

		private void cbContainsColName_CheckedChanged(object sender, EventArgs e)
		{
			GlobalObject.XmlConfigChain[this.GetType(), "cbContainsColName"] = cbContainsColName.Checked.ToString();
		}

		private void cbContainsDBIID_CheckedChanged(object sender, EventArgs e)
		{
			GlobalObject.XmlConfigChain[this.GetType(), "cbContainsDBIID"] = cbContainsDBIID.Checked.ToString();
		}

		private void cbContainsDBIName_CheckedChanged(object sender, EventArgs e)
		{
			GlobalObject.XmlConfigChain[this.GetType(), "cbContainsDBIName"] = cbContainsDBIName.Checked.ToString();
		}
	}
}
